<style lang="less" scoped>
@import "./menu.less";
.a {
  padding: 0 20;
}
</style>

<template>
  <div>
    <Row>
      <Col span="24">
      <Card>
        <p slot="title"
           style="height: 32px">
          <Button type="primary"
                  @click="alertAdd"
                  icon="md-add">新增</Button>
        </p>
        <div>
          <Table :loading="tableLoading"
                 :columns="columnsList"
                 :data="tableData"
                 border
                 disabled-hover></Table>

        </div>
      </Card>
      </Col>
    </Row>
    <Modal v-model="modalSetting.show"
           width="668"
           :styles="{top: '30px'}"
           @on-visible-change="doCancel">
      <p slot="header"
         style="color:#2d8cf0;">
        <Icon type="md-information-circle"></Icon>
        <span>{{formItem.id ? '编辑' : '新增'}}菜单</span>
      </p>
      <Form ref="myForm"
            :rules="ruleValidate"
            :model="formItem"
            :label-width="80">
        <FormItem label="菜单名称"
                  prop="name">
          <Input v-model="formItem.name"
                 placeholder="请输入菜单名称"></Input>
        </FormItem>
        <FormItem label="父级菜单"
                  prop="fid">
          <Select v-model="formItem.fid"
                  filterable>
            <Option :value="0">顶级菜单</Option>
            <Option v-for="item in tableData"
                    :value="item.id"
                    :key="item.id">{{ item.showName }}</Option>
          </Select>
        </FormItem>
        <FormItem label="菜单URL"
                  prop="url">
          <Input v-model="formItem.url"
                 placeholder="请输入菜单URL">
          <span slot="prepend">admin/</span>
          </Input>
        </FormItem>
        <FormItem label="菜单排序"
                  prop="sort">
          <InputNumber :min="0"
                       v-model="formItem.sort"></InputNumber>
          <Tag color="error"
               style="margin-left:5px">数字越小越靠前</Tag>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text"
                @click="cancel"
                style="margin-right: 8px">取消</Button>
        <Button type="primary"
                @click="submit"
                :loading="modalSetting.loading">确定</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import api from '@/api/menu';
import treetable_expand from './components/treetable_expand'
const editButton = (vm, h, currentRow, index) => {
  return h('Button', {
    props: {
      type: 'primary'
    },
    style: {
      margin: '0 5px'
    },
    on: {
      'click': () => {
        vm.formItem.id = currentRow.id;
        vm.formItem.name = currentRow.name;
        vm.formItem.fid = currentRow.fid;
        vm.formItem.url = currentRow.url.slice(6);
        vm.formItem.sort = currentRow.sort;
        vm.modalSetting.show = true;
        vm.modalSetting.index = index;
      }
    }
  }, '编辑');
};
const deleteButton = (vm, h, currentRow, index) => {
  return h('Poptip', {
    props: {
      confirm: true,
      title: '您确定要删除这条数据吗? ',
      transfer: true
    },
    on: {
      'on-ok': () => {
        api.delMenu({ id: currentRow.id }).then(res => {
          if (!res) {
            vm.tableData.splice(index, 1);
          }
        })
      }
    }
  }, [
      h('Button', {
        style: {
          margin: '0 5px'
        },
        props: {
          type: 'error',
          placement: 'top',
          loading: currentRow.isDeleting
        }
      }, '删除')
    ]);
};
export default {
  name: 'system_menu',
  data () {
    return {

      treeData: {
      },
      columnsList: [
        {
          title: 'ID',
          type: 'index',
          width: 65,
          align: 'center',
        },
        {  //添加的expand
          type: 'expand',
          // width: 1,
          width: 20,
          render: (h, params) => {
            return h(treetable_expand, {
              style: {
                padding: 0
              },
              props: {
                row: params.row,
                listcolumns: this.columnsList
              }
            })
          }
        },

        {
          title: '菜单名称',
          align: 'left',
          key: 'name',
          render: (h, params) => {
            let _this = this
            let iClass = '';
            if (!params.row._disableExpand) {
              iClass = this.tableData[params.index]._expanded ? 'ivu-icon-ios-folder-open' : 'ivu-icon-md-folder'
            } else {
              iClass = 'ivu-icon-md-document'
            }
            iClass += ' ivu-icon'
            let padding = (params.row.lv * 20) + 'px'

            return (
              <div style={{ fontSize: '14px', paddingLeft: `${padding}` }}
                onClick={
                  res => {
                    // 这个因为表格数据是按序号来的  所以expand的序号不存在 所以无法打开正确层级菜单 所以先放弃了 留着以后有空弄
                    // console.log(params)
                    // console.log(params.index)
                    console.log(params.row.index)
                    console.log(_this.tableData)
                    // 这么做好像可以 判断级别
                    // _this.tableData[params.index]['children'][0] = params.row
                    // params.row._expanded = true
                    // params.row.splice();
                    // this.tableData.splice();
                    // let a= this.$forceUpdate(); 
                    // this.$router.go(0)
                    // console.log(a)
                    // this.tableData.splice();
                    // let newAttr = !this.tableData[params.row.id]._expanded
                    // // params.index 这个有问题所以导致总是出错
                    // this.tableData[params.row.id]._expanded = newAttr
                  }
                }
              >
                <i style={{ color: '#FED084', fontSize: '16px', marginRight: '5px' }} class={iClass}></i> <span>{params.row.name}</span>
              </div >
            )
          }
        },
        {
          title: '排序',
          align: 'center',
          key: 'sort',
          width: 80
        },
        {
          title: '菜单URL',
          align: 'left',
          key: 'url',
          width: 200
        },
        {
          //  type: 'selection',
          title: '状态',
          align: 'center',
          key: 'hide',
          width: 100
        },
        {
          title: '操作',
          type: 'action',
          align: 'center',
          key: 'handle',
          width: 200,
          actions: [{
            type: 'primary',
            text: '编辑'
          }],
          handle: ['edit', 'delete']
        }
      ],
      tableLoading: false,
      tableData: [],
      modalSetting: {
        show: false,
        loading: false,
        index: 0
      },
      formItem: {
        name: '',
        fid: 0,
        url: '',
        sort: 0,
        id: 0
      },
      ruleValidate: {
        name: [
          { required: true, message: '菜单名称不能为空', trigger: 'blur' }
        ]
      }
    };
  },
  components: {
    treetable_expand
  },
  created () {
    this.init();
    this.getList();
  },
  methods: {
    init () {
      let vm = this;
      this.columnsList.forEach(item => {
        if (item.handle) {
          item.render = (h, param) => {
            let currentRowData = vm.tableData[param.index];
            return h('div', [
              editButton(vm, h, currentRowData, param.index),
              deleteButton(vm, h, currentRowData, param.index)
            ]);
          };
        }
        if (item.key === 'hide') {
          item.render = (h, param) => {
            let currentRowData = vm.tableData[param.index];
            return h('i-switch', {
              attrs: {
                size: 'large'
              },
              props: {
                'true-value': 1,
                'false-value': 0,
                value: currentRowData.hide
              },
              on: {
                'on-change': function (status) {
                  api.changeStatus({
                    status: status,
                    id: currentRowData.id
                  })
                }
              }
            }, [
                h('span', {
                  slot: 'open'
                }, '隐藏'),
                h('span', {
                  slot: 'close'
                }, '显示')
              ]);
          };
        }
      });
    },
    alertAdd () {
      this.modalSetting.show = true;
    },
    submit () {
      let self = this;
      this.$refs['myForm'].validate((valid) => {
        if (valid) {
          self.modalSetting.loading = true;
          let target = '';
          if (this.formItem.id === 0) {
            target = 'Menu/add';
          } else {
            target = 'Menu/edit';
          }
          api.modifyMenu(target, this.formItem).then(() => {
            self.getList();
            self.cancel()
          })
        }
      });
    },
    cancel () {
      this.modalSetting.show = false;
    },
    doCancel (data) {
      if (!data) {
        this.formItem.id = 0;
        this.$refs['myForm'].resetFields();
        this.modalSetting.loading = false;
        this.modalSetting.index = 0;
      }
    },
    async getList () {
      this.tableLoading = true;
      this.tableData = await api.getMenuList();
      this.treeData.lists = await api.getMenuList();
      this.tableLoading = false;
    }
  }
};
</script>
